package com.zmx.patients.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.adapter.AllPatientApadter;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.OrderDetails;
import com.zmx.patients.pojo.Patient;
import com.zmx.patients.utils.AllUtil;
import com.zmx.patients.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 患者列表
 */
public class AllPatientActivity extends BaseActivity {

    @BindView(R.id.reLayout)
    RelativeLayout reLayout;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.next)
    Button next;
    @BindView(R.id.add)
    Button add;


    private AllPatientApadter adapter;
    private List<Patient> list;
    private OrderDetails od;
    private String pID="";


    @Override
    protected int getLayoutId() {
        return R.layout.activity_all_patient;
    }

    @Override
    protected void initViews() {

        od = (OrderDetails) this.getIntent().getSerializableExtra("od");
        Log.e("医生名字", "名字" + od.getDoctor().getName());
        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        list = new ArrayList<>();
        adapter = new AllPatientApadter(this);
        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 2));
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                adapter.setItemChecked(listPosition);
                pID = list.get(listPosition).getId();

            }
        });

        getData();

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    Log.e("数据", "数据" + msg.obj);

                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());

                        list.clear();
                        if (jsonObject.getInt("code") == 1){

                            JSONArray array = jsonObject.getJSONArray("data");
                            Gson g = new Gson();
                            for (int i = 0; i < array.length(); i++) {

                                JSONObject object = array.getJSONObject(i);
                                Patient p = g.fromJson(object.toString(), Patient.class);
                                list.add(p);

                            }
                            adapter.setListAndNotifyDataSetChanged(list);

                        }else{
                            new AlertDialog.Builder(mActivity)
                                    .setTitle("温馨提示")
                                    .setMessage("请添加患者信息")
                                    .setPositiveButton("确定",(dialogInterface, i) -> {

                                        Bundle bundle = new Bundle();
                                        bundle.putString("relation", "4");
                                        startActivity(AddPatientActivity.class,bundle);

                                    })
                                    .show().setCancelable(true);
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;


            }

        }
    };


    @Override
    protected void onRestart() {
        super.onRestart();
        getData();
    }


    /**
     * 获取所有患者信息
     */
    public void getData() {


        List<String> ls = new ArrayList<>();
        ls.add("0");

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "patientList");
        params.put("data[patient_id]", "0");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 1, 404);

    }

    @OnClick({R.id.next, R.id.add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.next:

                if(!pID.equals("")){

                    od.setPatientId(pID);
                    Intent intent = new Intent(mActivity,OrderPayActivity.class);
                    intent.putExtra("od",od);
                    startActivity(intent);

                }else{

                    Toast("请选择患者");

                }

                break;
            case R.id.add:
                break;
        }
    }
}
